package org.example.doctorapi.server.Imp;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang3.StringUtils;
import org.example.doctorapi.data.SysUser;
import org.example.doctorapi.mapper.SysUserMapper;
import org.example.doctorapi.server.SysUserServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class SysUserServerImp implements SysUserServer {
    @Autowired
    private PasswordEncoder encoder;
    @Autowired
    private SysUserMapper sysUserMapper;
    @Override
    public Page<SysUser> getDict(SysUser sysUser) {
        Page<SysUser> page = new Page<>();
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(StringUtils.isNotBlank(sysUser.getUserName()),"user_name",sysUser.getUserName());
        List<SysUser> userList = sysUserMapper.selectList(queryWrapper);
        page.setRecords(userList);
        page.setSize(sysUser.getPageSize());
        page.setCurrent(sysUser.getPageNum());
        page.setTotal(userList.size());
        return page;
    }

    @Override
    public void insertOne(SysUser sysUser) {
        sysUserMapper.insert(sysUser);
    }

    @Override
    public void updateOne(SysUser sysUser) {
        sysUserMapper.updateById(sysUser);
    }

    @Override
    public void deleteList(List<Integer> ids) {
        sysUserMapper.deleteBatchIds(ids);
    }

    @Override
    public void updatePassword(Integer userId, String password) {
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",userId);
        SysUser sysUser = sysUserMapper.selectOne(queryWrapper);
        String password1 = sysUser.getPassword();
        boolean matches = encoder.matches(password1, password);
        if (matches){
            String encode = encoder.encode(password);
            sysUser.setPassword(encode);
            sysUserMapper.updateById(sysUser);
        }
    }
}
